package com.umpay.controller.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.umpay.dict.LoggerDict;
import com.umpay.log.mpsp.MpspLogger;
import com.umpay.util.StringUtils;

/**
 * 存活监控
 * 
 * @ClassName KeepAliveController
 * @Description TODO
 * @author FENG JUN LIU
 * @Date 2018年2月28日
 * @version 1.0.0
 */
@RestController
public class KeepAliveController {

    private static final Logger log = LogManager.getLogger(AbstractController.class);
    private static final Set<String> keys;
    static {
        keys = getConfig();
    }

    private static Set<String> getConfig() {
        Set<String> set = new LinkedHashSet<String>();
        String info = getInfoByConfig().trim();
        if (StringUtils.isNotEmpty(info)) {
            String[] ss = info.split("\\|");
            for (String s : ss) {
                String key = StringUtils.trim(s);
                if (StringUtils.isNotEmpty(key)) {
                    set.add(key);
                }
            }
        }
        return set;
    }

    private static String getInfoByConfig() {
        FileInputStream input = null;
        FileChannel channel = null;
        StringBuilder builder = new StringBuilder();
        try {
            String path = MpspLogger.class.getClassLoader().getResource("config/mpsp.properties").getPath();
            input = new FileInputStream(new File(path));
            channel = input.getChannel();
            ByteBuffer bf = ByteBuffer.allocate(20);
            int length = -1;

            try {
                while ((length = channel.read(bf)) != -1) {
                    bf.flip();
                    byte[] bts = new byte[bf.remaining()];
                    bf.get(bts);
                    builder.append(new String(bts, "UTF-8"));
                    bf.clear();
                }
                channel.close();
            } catch (IOException e) {
            }
        } catch (FileNotFoundException e) {
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (channel !=null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return builder.toString();
    }

    /**
     * 获取简要日志信息
     * 
     * @Description (TODO这里用一句话描述这个方法的作用)
     * @param request
     * @param response
     * @return
     */
    private static String getMpspMsg(HttpServletRequest request, String rpid, String retCode, String retMsg) {
        StringBuilder builder = new StringBuilder();
        for (String key : keys) {
            String value = "";
            if ("url".equals(key)) {
                value = request.getRequestURL().toString();
            } else if ("method".equals(key)) {
                value = request.getMethod();
            } else if ("time".equals(key)) {
                long begin = (Long) request.getAttribute(LoggerDict.START_TIME);
                long time = System.currentTimeMillis() - begin;
                value = time + "ms";
            } else if ("rpid".equals(key)) {

            } else if ("ret_code".equals(key)) {
                value = retCode;
            } else if ("ret_msg".equals(key)) {
                value = retMsg;
            }

            builder.append(value).append(',');
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }

    @RequestMapping("/consumeBusi/KeepAlive/")
    public Map<String, String> KeepAlive(HttpServletRequest request) {
        log.info("存活监控请求...");
        String rpid = Thread.currentThread().getName();
        String retCode = "0000";
        String retMsg = "存活监控成功";
        Map<String, String> map = new HashMap<String, String>();
        map.put("retCode", retCode);
        map.put("retMsg", retMsg);
        request.setAttribute("notPrintMpsp", "true");
        MpspLogger.printKeepLiveMpspMsg(getMpspMsg(request, rpid, retCode, retMsg));
        return map;
    }
}
